import * as fs from 'fs-extra';
import moment = require('moment');
import { createLogger, format, transports } from 'winston';
import { logDir } from '../config';
const DailyRotateFile = require('winston-daily-rotate-file');

fs.ensureDir(logDir, () => { });

const transport_web = new DailyRotateFile({
    filename: logDir + '/web-%DATE%.log',
    level: 'info',
    datePattern: 'YYYY-MM-DD-HH',
    zippedArchive: true,
    maxSize: '20m',
    maxFiles: '14d',
});
const transport_error = new DailyRotateFile({
    filename: logDir + '/error-%DATE%.log',
    level: 'error',
    datePattern: 'YYYY-MM-DD-HH',
    zippedArchive: true,
    maxSize: '20m',
    maxFiles: '14d',
});
const logger_web = createLogger({
    level: 'info',
    format: format.simple(),
    transports: [
        //
        // - Write to all logs with level `info` and below to `combined.log`
        // - Write all logs error (and below) to `error.log`.
        //
        // new transports.File({ filename: logDir + '/error.log', level: 'error' }),
        // new transports.File({ filename: logDir + '/combined.log' })
        transport_web,
    ],
});
const logger_error = createLogger({
    level: 'error',
    format: format.simple(),
    transports: [
        //
        // - Write to all logs with level `info` and below to `combined.log`
        // - Write all logs error (and below) to `error.log`.
        //
        // new transports.File({ filename: logDir + '/error.log', level: 'error' }),
        // new transports.File({ filename: logDir + '/combined.log' })
        transport_error,
    ],
});

//
// If we're not in production then log to the `console` with the format:
// `${info.level}: ${info.message} JSON.stringify({ ...rest }) `
//
if (process.env.NODE_ENV !== 'production') {
    logger_web.add(new transports.Console({
        format: format.simple(),
    }));
}

export const requestLog = (str) => {
    const now = moment().format('YYYY-MM-DD HH:mm:ss');
    logger_web.info(now + str);
};
export const errorLog = (str) => {
    const now = moment().format('YYYY-MM-DD HH:mm:ss');
    logger_error.error(now + ' ' + str);
};
